//
//  TenderBaseForm.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2024/9/26.
//  Copyright © 2024 zwb. All rights reserved.
//

import UIKit

class ZyaTenderBaseForm: UIViewController,refreshable,getDepositRemainable {
    lazy var tableView: UITableView = {
        let v = UITableView()
        return v
    }()
    lazy var footer:UIView = {
        let v = UIView(frame:CGRect(x:0,y:0,width: KSGlobal.screenW,height:KSGlobal.screenH))
        v.backgroundColor = Theme.awModuleBgColor
        return v
    }()
    lazy var footbg :FormView = {
        let v = FormView(frame:CGRect(x:BgLeading,y:10,width: KSGlobal.screenW - BgLeading * 2,height:KSGlobal.screenH))
        v.backgroundColor = .clear
        v.layer.cornerRadius = ItemCornerRadius
        return v
    }()
    
    lazy var submitButton: KSUIButton = {
        let v = KSUIButton(titlex: "确认")
        v.button.backgroundColor = Theme.primaryColor()
        v.button.layer.cornerRadius = 23
        
        return v
    }()
    var sectionx :ItemSectionView = {
        let v = ItemSectionView()
        v.lab.isHidden = true
        v.btn.isHidden = true
        return v
    }()
    var tbinfo_V: TbInfoNewView = {
        var v = TbInfoNewView()
        return v
    }()
    var one = ZyaZtbContentModel(JSON: ["":""])!
    var z_tb_id = ""
    var z_zb_id = ""
    
    var excuteType = OperateType.add
    var depositRemain = 0.0
    
    
    var headView = UIView()
    var origTbPrice = 0.0
    
    //    //    z_status   当前出价单据状态     0 未中标   1 已中标   2 已放弃
    //    //    z_zb_status  采购状态   0:未开始;   1:已中标;   2:进行中;    3:已结束;      4:已流标
    //    /// 判断时用这两个状态，因为公用的因素，这里字段需要整理
    //    var z_zb_status = "0"
    //    var z_tb_status = "0"
  
    lazy var timeflagView:ZyaTimeFlagView = {
        let v = ZyaTimeFlagView(frame:CGRect(x:0,y:0,width: self.view.frame.width,height: timeflagH))
        return v
    }()
    lazy var zbTitleView:TitleChujiaImgView = {
        let v = TitleChujiaImgView( withImg: false)
        return v
    }()
    var topH:CGFloat = 0
    var itemdw :KSFormHItem = {
        let appe = KSFormHAppear()
            .contentTrailing(rightPP)
            .disableStyleContentGray(true)
            .contentHight(contentHHH)
            .contentFont(UIFont.systemFont(ofSize: 17))
        let v = KSFormHItem(title: "出价单位",appearance:appe )
        v.disabled = true
        return v
    }()
    // 出价人  25-01-07改为可编辑
    var itemr :KSFormHItem = {
        let appe = KSFormHAppear()
            .contentTrailing(rightPP)
            .disableStyleContentGray(true)
            .contentHight(contentHHH)
            .contentFont(UIFont.systemFont(ofSize: 17))
        let v = KSFormHItem(title: "出价人",appearance:appe )
        return v
    }()
    var itemtip :KSFormHItem = {
        let appe = KSFormHAppear()
            .contentTrailing(rightPP)
            .tipStr("-")
            .contentHight(70)
            .contentFont(UIFont.systemFont(ofSize: 17))
        let v = KSFormHItem(title: "",appearance:appe,type: .tempTip )
        v.disabled = true
        return v
    }()
    var itemstatus :KSFormHItem = {
        let appe = KSFormHAppear()
            .contentTrailing(rightPP)
            .tipStr("-")
            .contentHight(contentHHH)
            .contentFont(UIFont.systemFont(ofSize: 17))
        let v = KSFormHItem(title: "",appearance:appe,type: .tempTip )
        v.disabled = true
        return v
    }()
    var itemaddr :KSFormHItem = {
        let appe = KSFormHAppear()
            .contentTrailing(rightPP)
        
            .contentHight(contentHHH)
            .contentFont(UIFont.systemFont(ofSize: 17))
        let v = KSFormHItem(title: "地址",appearance:appe )
        
        return v
    }()
    
    var itemaddrDet :KSFormHItem = {
        let appe = KSFormHAppear()
            .contentTrailing(rightPP)
            .assistImgStr("tenderBJ")
            .contentHight(contentHHH)
            .contentFont(UIFont.systemFont(ofSize: 17))
        let v = KSFormHItem(title: "详细地址",appearance:appe )
        
        return v
    }()
    var itemdh :KSFormHItem = {
        let appe = KSFormHAppear()
            .contentTrailing(rightPP)
            .disableStyleContentGray(true)
            .phoneInput(true)
            .contentHight(contentHHH)
            .contentFont(UIFont.systemFont(ofSize: 17))
        let v = KSFormHItem(title: "联系电话",appearance:appe )
        v.disabled = true
        return v
    }()
    var itembzj :KSFormHItem = {
        let appe = KSFormHAppear()
            .contentTrailing(rightPP)
            .disableStyleContentGray(true)
            .phoneInput(true)
            .contentHight(contentHHH)
            .contentFont(UIFont.systemFont(ofSize: 17))
        let v = KSFormHItem(title: "保证金余额",appearance:appe )
        v.disabled = true
        return v
    }()
    var itemjg :KSFormHItem = {
        let appe = KSFormHAppear()
            .contentTrailing(rightPP)
            .contentHight(contentHHH)
        let v = KSFormHItem(title: "出价价格",appearance:appe ,type: .countV)
        return v
    }()
    var itemjg_input :KSFormHItem = {
        let appe = KSFormHAppear()
            .contentTrailing(rightPP)
            .fourDemiInput(true)
            .contentHight(contentHHH)
            .contentFont(UIFont.systemFont(ofSize: 17))
        let v = KSFormHItem(title: "出价价格",appearance:appe )
        return v
    }()
    var itemSM :KSFormHItem = {
        let appe = KSFormHAppear()
            .contentTrailing(rightPP)
            .assistImgStr("tenderBJ")
            .contentHight(contentHHH)
            .contentFont(UIFont.systemFont(ofSize: 17))
        let v = KSFormHItem(title: "出价说明",appearance:appe )
        return v
    }()
    var itemsj :KSFormHItem = {
        let appe = KSFormHAppear()
            .contentTrailing(rightPP)
            .disableStyleContentGray(true)
            .contentHight(contentHHH)
            .contentFont(UIFont.systemFont(ofSize: 17))
        let v = KSFormHItem(title: "出价时间",appearance:appe )
        v.disabled = true
        return v
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
       
        self.insertIds2Update()
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = .white
        self.title = "出价"
        
        let navH = self.navigationController.isSome ? self.navigationController!.navigationBar.frame.height : 0
        topH = UIApplication.shared.statusBarFrame.height + navH
        
        view.addSubview(timeflagView)
      
        view.addSubview(tableView)
        timeflagView.frame = CGRect(x:0,y: topH,width: self.view.frame.width,height:  timeflagH)
        
        tableView.frame = CGRect(x:0,y: timeflagView.ks_maxY,width: self.view.frame.width,height:  view.ks_maxY - timeflagView.ks_maxY)

        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 150, right: 0)
        
        
        
        footer.addSubview(footbg)
        
        
        if excuteType == .add {
            
        } else {
            navigationItem.rightBarButtonItem = UIBarButtonItem(title:  "放弃", style: .done, target: self, action: #selector(deleteAction))
        }
        
        
        
        self.network()
        
        NotificationCenter.default.addObserver(self, selector: #selector(servertimeNotification(_:)), name: Notification.Name("servertime_notification"), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(newestBillStatusNotification(_:)), name: Notification.Name(newestBillStatus_notification), object: nil)
        
        
    }
    @objc func newestBillStatusNotification(_ notification: Notification) {
        // 从通知中获取用户信息
        if let userInfo = notification.userInfo,
           let arr = userInfo["newestBillStatus_data"] as? [NewestModel_Z] {
            
            
            let ddd = arr.filter{$0.idKey == self.one.zZbId}
            
            if ddd.count > 0 {
                self.one.zParallel = ddd.first!.zParallel
                self.one.zMyPrice = ddd.first!.zMyPrice
                if ddd.first!.zEndDate.unwrap != "" {
                    self.one.zEndDate = ddd.first!.zEndDate
                }
                if ddd.first!.zOvertimedNum.unwrap != "" {
                    self.one.zOvertimedNum = ddd.first!.zOvertimedNum
                }
                self.one.zMyPriceRank = ddd.first!.zMyPriceRank
                self.one.zBidCount = ddd.first!.zBidCount
                self.one.zPriceRank = ddd.first!.zPriceRank
                
            }
            self.zbTitleView.setChujiaShow(title: self.one.zTitle.unwrap, count: self.one.zBidCount.unwrap, price: self.one.zMyPrice.unwrap,unit: self.one.zUnitNm.unwrap, rank: self.one.zMyPriceRank.unwrap,z_end_price_rank: self.one.zEndPriceRank.unwrap,z_parallel: self.one.zParallel.unwrap)
            self.tableView.reloadData()
            
        }
    }
    var handleStatus = "1" {
        didSet {
            if oldValue != handleStatus {
                self.network()
            }
        }
    }
    @objc func servertimeNotification(_ notification: Notification) {
        // 从通知中获取用户信息
        if let userInfo = notification.userInfo,
           let valueServerDate = userInfo["servertime_data"] as? Date {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            var endDate = Date()
            if let endD = dateFormatter.date(from: self.one.zEndDate.unwrap) {
                endDate = endD
            }
            var startDate = Date()
            if let startD = dateFormatter.date(from: self.one.zBeginDate.unwrap) {
                startDate = startD
            }
            var btnName = ""
            let timeNowToEnd = Int(endDate.timeIntervalSince1970-valueServerDate.timeIntervalSince1970)
            let timeNowToStart = Int(startDate.timeIntervalSince1970-valueServerDate.timeIntervalSince1970)
            var timeTipStr:String = ""
            if timeNowToStart > 0 {
                self.handleStatus = "1"
                timeTipStr = "\(self.one.zBeginDate.unwrap)开始"
                btnName = "未开始"
            } else if timeNowToEnd < 0 {
                self.handleStatus = "3"
                timeTipStr = "\(self.one.zEndDate.unwrap)结束"
                btnName = "已结束"
                if timeNowToEnd > -15 && timeNowToEnd%3 == 0 {
                    self.network()
                }
            } else {
                self.handleStatus = "2"
                // 进行中
                let nowtt = Date.nowTimeToSecond
                let svvvStr = dateFormatter.string(from: valueServerDate)
                timeTipStr = "距结束" + Date.getHHMMSSFormSS(seconds: timeNowToEnd)
                btnName = "进行中"
            }
     
            self.timeflagView.setTimeFlagInfo(status: btnName, countDown: timeTipStr,model: one)
        
            
            
            
//            let dateFormatter = DateFormatter()
//            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
//            var endDate = Date()
//            if let endD = dateFormatter.date(from: self.one.zEndDate.unwrap) {
//                endDate = endD
//            }
//            
//            let timeNumber = Int(endDate.timeIntervalSince1970-valueServerDate.timeIntervalSince1970)
//            
//            if timeNumber > 0 {
//                self.refreshBtn(enable: true)
//                
//                
//                self.timeflagView.setTimeFlagInfo(status: "进行中", countDown: "距结束\(Date.getHHMMSSFormSS(seconds: timeNumber))",model: one)
//                
//            } else {
//                self.timeflagView.setTimeFlagInfo(status: "已结束", countDown: " \(self.one.zEndDate.unwrap)结束",model: one)
//                
//                
//                self.refreshBtn(enable: false)
//                
//            }
            
            
        }
    }
//    func refreshBtn(enable:Bool) {
//        if enable {
//            self.submitButton.button.backgroundColor = Theme.primaryColor()
//            self.submitButton.button.isUserInteractionEnabled = true
//        } else {
//            self.submitButton.button.backgroundColor = .lightGray
//            self.submitButton.button.isUserInteractionEnabled = false
//        }
//        
//    }
    func performRow () {
        
        
        setOriPrice()
        configView()
        configAction()
        configDataSource()
        
    }
    //子类实现
    func addDaochang() {
        
    }
    
    func setOriPrice() {
        var startPrice = 0.0
       
        if doubleTran(self.one.zPrice) > 0 {
            startPrice = doubleTran(self.one.zPrice)
        } else if self.one.zZbPrice.doubleWrap > 0 {
            startPrice = self.one.zZbPrice.doubleWrap
        }
        origTbPrice = startPrice
    }
    
    func configView() {
        
        
            footbg.removeAllItem()
            
            if self.depositRemain < self.one.zDepositMoney.doubleWrap {
                footbg.add(itemtip)
            }
            
            footbg.add(itemdw).add(itemr).add(itemdh).add(itembzj)
            
            var startPrice = 0.0
           
            if doubleTran(self.one.zPrice) > 0 {
                startPrice = doubleTran(self.one.zPrice)
            } else if self.one.zZbPrice.doubleWrap > 0 {
                startPrice = self.one.zZbPrice.doubleWrap
            }
          
            
            
            if doubleTran(self.one.zRange) == 0 {// 幅度为0，用手输入
                footbg.add(itemjg_input)
                
            } else {
                if startPrice == 0 { // 幅度不为0，但是起始报价为0，用手输入
                    
                    footbg.add(itemjg_input)
                    
                    
                } else { // 幅度不为0，起始报价也不为0，用加减按钮
                    var maxV:Double = 1000000
                    var minV:Double = 0.0
                    if self.one.zType.unwrap == "0" {  // 卖标 的时候  起始价为最小价
                        if startPrice > 0 {
                            minV = Double(startPrice)
                        }
                    } else {  // 买标  的时候  起始价为最高价
                        if startPrice > 0 {
                            maxV = Double(startPrice)
                        }
                    }
                    footbg.add(itemjg)
                    itemjg.setCountViewMax(maxV)
                    itemjg.setCountViewMin(minV)
                    itemjg.setFuduNumber(doubleTran(self.one.zRange))
                    
                    
                    
                }
                
            }
            
           addDaochang()
            
            footbg.add(itemaddr).add(itemaddrDet).add(itemSM)
       
            footbg.addSection(sectionx)
            footbg.add(submitButton)
            footer.ks_height = footbg.frame.maxY
            self.tableView.tableFooterView = footer
          
        
        
    }
    func configAction() {
        itemjg.countViewChangeClo = { str in
            self.one.zPrice = str
            self.configDataSource()
        }
        itemjg_input.textEndEditClo = { str in
            self.one.zPrice = str
            self.configDataSource()
        }
        submitButton.button.addTouchUpInSideAction {_ in
           
            self.saveAction()
        }
        itemr.textValueChangeClo = {str in
            self.one.zName = str
        }
        itemaddr.actionClosure = {
            let vc = ProvinceCityController(selectType: .city)
            vc.citySelectClosure = { province,city in
                
                self.one.zProvince = province
                self.one.zCity = city
                self.configDataSource()
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }
        itemaddrDet.textValueChangeClo = {str in
            self.one.zAddress = str
        }
        itemSM.textValueChangeClo = {str in
            self.one.zContent = str
        }
        
    }
    func configDataSource() {
        
        if self.excuteType == .add {
            if one.zTbCompany.unwrap == "" {
                one.zTbCompany = PersonInfo!.commpayNm
            }
            if one.zName.unwrap == "" {
                one.zName = PersonInfo!.faren
            }
            if one.zTel.unwrap == "" {
                one.zTel = PersonInfo!.providerTel
            }
//            if one.zSupplier.unwrap == "" {
//                one.zSupplier = PersonInfo!.faren
//            }
            if one.zAddress.unwrap == "" {
                self.one.zAddress = PersonInfo!.address
            }
            if one.zProvince.unwrap == "" {
                self.one.zProvince = PersonInfo!.prov
            }
            if one.zCity.unwrap == "" {
                self.one.zCity = PersonInfo!.city
            }
           
        }
        
        
        var tipStr = ""
        var tbTitle = "确认\(zyagetRest4Show(max: self.one.zMaxBidNo.unwrap, rest: self.one.zRestBidNo.unwrap))"
        
       var depositAndTryJudge = true
        
      
        if self.depositRemain < self.one.zDepositMoney.doubleWrap {
            // 保证金不足
            if one.zRemainTry.isSome && one.zRemainTry.unwrap != "0" {
                // 有试投次数
                tipStr = " 您的保证金不足，当前可免保证金试投，出价价格有效."
                tbTitle = "试出价(剩余\(one.zRemainTry.unwrap)次)"
                depositAndTryJudge = true
            } else {
                tipStr = "您的保证金不足，请先缴纳保证金，审核通过之后该出价才能生效。"
                depositAndTryJudge = false
            }
        } else {
            tipStr = ""
            depositAndTryJudge = true
        }
        
       
        itemtip.setTipStr(tipStr)
     
        itemSM.setVal(self.one.zContent)
     
        submitButton.button.setTitle(tbTitle, for: .normal)
        
        
        if (( (self.one.zStatus == "0")
              && self.one.zZbStatus == "2"  &&
              zyagetRest4Judge(max: self.one.zMaxBidNo.unwrap, rest: self.one.zRestBidNo.unwrap) ) 
            && depositAndTryJudge
            || self.excuteType == .add)
        {
            if submitButton.superview.isNone {
                footbg.insertx(submitButton, preItem: sectionx) {
                    footer.ks_height = footbg.frame.maxY
                    self.tableView.tableFooterView = footer
                }
            }
        } else {
            if submitButton.superview.isSome {
                footbg.removex(submitButton) {
                    footer.ks_height = footbg.frame.maxY
                    self.tableView.tableFooterView = footer
                }
            }
        }
        itemdw.setVal(one.zTbCompany)
        itemr.setVal(one.zName)
        itemdh.setVal(one.zTel)
        itembzj.setVal("\(self.depositRemain)")
        
        itemjg.appearance.tailDesc = "元/\(self.one.zUnitNm.unwrap)"
        itemjg.updateTailDesc()
        
        //        fjwoiefjo
        //todo 出价价格
        var startPrice = getStartPrice()
        var showPrice = startPrice == 0 ? "" : "\(startPrice)"
        
        itemjg.setCountVCurrentValue(startPrice)
        itemjg_input.setVal(showPrice)
        itemaddr.setVal(self.one.zProvince.unwrap + self.one.zCity.unwrap)
        
        
        itemaddrDet.setVal(self.one.zAddress)
        
        
        var titleStr = ""
        var color:String!
        if self.one.zStatus == "0" {
            titleStr = "出价状态：未中标"
            color = "aaaaaa"
        } else if self.one.zStatus == "1" {
            titleStr = "出价状态：已中标"
            color = "FF0000"
        } else {
            titleStr = "出价状态：已放弃"
            color = "aaaaaa"
        }
        
        itemstatus.setTipStr(titleStr,color: color,tipAligment: .center)
        
        
    }
    func getStartPrice() -> Double {
        var startPrice = 0.0
        
        if doubleTran(self.one.zPrice) > 0 {
            startPrice = doubleTran(self.one.zPrice)
        } else if self.one.zZbPrice.doubleWrap > 0 {
            startPrice = self.one.zZbPrice.doubleWrap
        }
        return startPrice
    }
    
    func network() {
        
        if z_tb_id == "" { // 还未出过价
            self.dealSome()
        } else {
            var api:API?
            api = API.queryMytenderTbInfo(z_tb_id: z_tb_id)
            KSNetwork.shared.doRequest(api!) { (data:BaseResult<ZyaZtbContentModel>) in
                if data.flag == TRUE {
                    if let info = data.info_object {
                        self.one = info
                        
                        self.dealSome()
                        
                        
                    }
                    
                    
                    
                } else {
                    
                }
            }
        }
        
        
    }
    func dealSome() {
     
        
        if self.one.zZbStatus != "2" { // 采购状态 为 进行中的时候才会有  放弃
            self.navigationItem.rightBarButtonItem = nil
        }
        if self.one.zStatus != "0" { // ----   出价状态为 未中标才有放弃
            self.navigationItem.rightBarButtonItem = nil
        }
         
        self.tbinfo_V.content1.multiLineTitleContentShow(contentStr: self.one.zbInfo.unwrap, fontx: 16)
        
        let tbHHH = self.tbinfo_V.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
        self.tbinfo_V.ks_height = tbHHH
        self.tbinfo_V.ks_width = KSGlobal.screenW
        
        let  zbtitleH:CGFloat = 65
        self.zbTitleView.frame = CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: zbtitleH)
        
        self.headView.addSubview(self.zbTitleView)
        
        
        self.tbinfo_V.ks_y = self.zbTitleView.ks_maxY
        
        self.headView.addSubview(self.tbinfo_V)
        
        
        self.zbTitleView.recordApi = API.tender(.queryTbRecordList(z_zb_id: self.z_zb_id, z_bid_id: self.one.zBidId.unwrap, z_staff_id: USERINFO.usrid.unwrap))
        
        
        
        self.zbTitleView.setChujiaShow(one:self.one,title: self.one.zTitle.unwrap, count: self.one.zBidCount.unwrap, price: self.one.zMyPrice.unwrap,unit: self.one.zUnitNm.unwrap, rank: self.one.zMyPriceRank.unwrap,z_end_price_rank: self.one.zEndPriceRank.unwrap,z_parallel: self.one.zParallel.unwrap)
        
        
        self.headView.frame = CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: tbHHH + zbtitleH)
        self.tableView.tableHeaderView = self.headView
        self.insertIds2Update()
        self.getDepositValue { (flag,value) in
            self.depositRemain = doubleTran(value)
            self.performRow()
        }
    }
    @objc func showRankTip() {
        var tipStr = ""
        if self.one.zType.unwrap == "0" {
            tipStr = "出价价格越高，排名越靠前"
        } else {
            tipStr = "出价价格越低，排名越靠前"
        }
        alertUtil(self, title: tipStr,withCancel: false, operateS: [nameAction(name: "确定", action: { (_) in
            
        })])
    }
    
    @objc func deleteAction() {
        
        let tipDesc =  "放弃会被认为恶意出价并且保证金不退回，是否确认放弃？"
        
        alertUtil(self, title: tipDesc, operateS: [nameAction(name: "确定", action: { (_) in
            var api:API?
            
            api = API.deleteMytenderTbInfo(id_key: self.z_tb_id)
            
            KSNetwork.shared.doRequest(api!) { (data:BaseResult<OperateResult>) in
                if data.flag == TRUE {
                    if let clo = self.refreshClosure {
                        clo()
                    }
                    self.navigationController?.popViewController(animated: true)
                    
                } else {
                    KSToast(data.message.unwrap)
                }
            }
        })])
        
    }
    func  getAlertTipStr() -> String {
        "本次会消耗一次出价机会，您的出价价格是\(self.one.zPrice.unwrap)元，请再次核对您的出价价格，是否立即参与出价？"
    }
    
    func noNullPass() -> Bool {
        
        let vali = Validation()
        vali.required(value: one.zTbCompany, msg: "出价单位不为空")
        vali.required(value: one.zName, msg: "出价人不为空")
        vali.required(value: one.zTel, msg: "联系电话不为空")
        vali.required(value: one.zPrice, msg: "出价价格不为空")
        
        
        guard vali.validate() else {
            return false
        }
        return true
    }
    
    func judgePrice() -> Bool {
        if self.one.zType.unwrap == "0" {  // 卖标
            
            if  doubleTran(self.one.zPrice) >= self.origTbPrice {
                return true
            } else {
                KSToast("出价价格不能低于参考价格或上次出价价格")
                return false
            }
        } else {  // 买标
            
            if doubleTran(self.one.zPrice) <= self.origTbPrice {
                return true
            } else {
                KSToast("出价价格不能高于参考价格或上次出价价格")
                return false
            }
        }
    }
    
    
    func saveAction() {
        
        view.endEditing(true)
        
        if self.one.zZbId.unwrap.isEmpty {
            self.one.zZbId = self.z_zb_id
        }
        if noNullPass() {
            if doubleTran(self.one.zRange) == 0 {
                
            } else {
                // 这里取余数判断倍数，防止被小数点影响计算，乘100
                let blowprice = (doubleTran(self.one.zPrice) * 10000).roundTo(0)
                let blowrange = (doubleTran(self.one.zRange) * 10000).roundTo(0)
                let diviResult = blowprice.truncatingRemainder(dividingBy: blowrange).roundTo(0)
                guard  diviResult == 0.0 else {
                    
                    // 去除整数限制: http://59.59.58.36:3316/zentao/task-view-23490.html 
//                    if self.one.zRange == "1" {
//                        KSToast("出价价格必须为整数")
//                    } else {
 
                        KSToast("出价价格必须为\(self.one.zRange.unwrap)的倍数",duration: 1.6)
//                    }
                    return
                }
                
                
            }
            
            
            
            
            
            if self.one.zZbPrice.doubleWrap > 0.0 {
                
                if self.one.zType.unwrap == "0" {  // 卖标
                    guard doubleTran(self.one.zPrice) >= self.one.zZbPrice.doubleWrap else {
                        KSToast("出价价格不能低于采购价格")
                        return
                    }
                    
                } else {  // 买标
                    guard doubleTran(self.one.zPrice) <= self.one.zZbPrice.doubleWrap else {
                        KSToast("出价价格不能高于采购价格")
                        return
                    }
                    
                }
                
            }
            
            if self.origTbPrice > 0 {
                guard judgePrice() else {
                    return
                }
            }
            guard doubleTran(self.one.zPrice) > 0 else {
                KSToast("出价价格不能为0")
                return
            }
            
            if self.excuteType == .add {
                alertUtil(self, title: getAlertTipStr(), operateS: [nameAction(name: "确定", action: { (_) in
                    
                    var api:API?
                    
                    api = API.saveMytenderTbInfo(data: dictionaryToJson(self.one.dictionaryRepresentation()))
                    
                    
                    KSNetwork.shared.doRequest(api!) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            if let info = data.info_object {
                                
                                self.z_tb_id = info.z_tb_id.unwrap
                                self.excuteType = .fix
                                if let message = data.message {
                                    alertUtil(self, title: message,withCancel: false, operateS: [nameAction(name: "确定", action: { (_) in
                                        
                                        
                                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: CALL_tenderinfo_REFRESH), object: nil)
                                        self.network()
                                        //                                        for controller in (self.navigationController?.viewControllers)! {
                                        //                                            if controller.isKind(of: TenderInfoController.self) == true {
                                        //                                                _ = self.navigationController?.popToViewController(controller, animated: true)
                                        //                                                break
                                        //                                            }
                                        //                                        }
                                        
                                        
                                    })])
                                } else {
                                    
                                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: CALL_tenderinfo_REFRESH), object: nil)
                                    self.network()
                                    //                                    for controller in (self.navigationController?.viewControllers)! {
                                    //                                        if controller.isKind(of: TenderInfoController.self) == true {
                                    //                                            _ = self.navigationController?.popToViewController(controller, animated: true)
                                    //                                            break
                                    //                                        }
                                    //                                    }
                                    
                                }
                                
                                
                                
                                
                            } else {
                                KSToast("缺少出价id")
                            }
                            
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
                })])
            } else {
                alertUtil(self, title: getAlertTipStr(), operateS: [nameAction(name: "确定", action: { (_) in
                    
                    
                    
                    var api:API?
                    
                    api = API.updateMytenderTbInfo(data: dictionaryToJson(self.one.dictionaryRepresentation()))
                    
                    
                    
                    KSNetwork.shared.doRequest(api!) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            
                            
                            if let message = data.message {
                                alertUtil(self, title: message,withCancel: false, operateS: [nameAction(name: "确定", action: { (_) in
                                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: CALL_tenderinfo_REFRESH), object: nil)
                                    self.network()
                                    //                                    self.navigationController?.popViewController(animated: true)
                                })])
                            } else {
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: CALL_tenderinfo_REFRESH), object: nil)
                                self.network()
                                //                                self.navigationController?.popViewController(animated: true)
                            }
                            
                            
                            
                            
                            
                            
                            
                            
                        } else {
                            KSToast(data.message.unwrap)
                        }
                    }
                })])
            }
        }
        
        
        
        
    }
    
    func insertIds2Update() {
        
        GetNewestUtil_Z.shared.appendIds(ids: [self.z_zb_id],type: .TB)
        
    }
    
    
    
    
}
